import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Card, Button, Space, Typography, Tag, Avatar, Tooltip } from 'antd';
import {
  EyeOutlined,
  SettingOutlined,
  UserAddOutlined,
  TeamOutlined,
  CalendarOutlined,
  GlobalOutlined,
  HomeOutlined
} from '@ant-design/icons';
import networkService from '../../../../services/network';
import axios from 'axios';
import Toast from '../../../../components/Toast';

const { Text } = Typography;

const NetworkCard = ({ network, userRole, showJoinButton = false, onNetworkJoined }) => {
  const navigate = useNavigate();
  const [joinLoading, setJoinLoading] = useState(false);
  const [showToast, setShowToast] = useState(false);
  const [toastMessage, setToastMessage] = useState('');

  // 状态标签
  const getStatusTag = (status) => {
    const statusConfig = {
      active: { color: 'success', text: '活跃' },
      inactive: { color: 'default', text: '不活跃' },
      pending: { color: 'warning', text: '等待中' }
    };
    const config = statusConfig[status] || { color: 'default', text: '未知' };
    return <Tag color={config.color} style={{ borderRadius: '12px', fontWeight: 500 }}>{config.text}</Tag>;
  };

  // 格式化日期
  const formatDate = (dateString) => {
    return new Date(dateString).toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  const showToastMessage = (message) => {
    setToastMessage(message);
    setShowToast(true);
  };

  // 处理加入网络
  const handleJoinNetwork = async (e) => {
    e.stopPropagation(); // 阻止事件冒泡
    
    try {
      setJoinLoading(true);
      const response = await networkService.joinNetwork(network.networkId);
      
      if (response.data.code === 200) {
        showToastMessage('成功加入局域网');
        // 调用父组件的回调函数来刷新网络列表
        if (onNetworkJoined) {
          onNetworkJoined(network.networkId);
        }
      } else {
        showToastMessage(response.data.message || '加入失败，请稍后重试');
      }
    } catch (err) {
      // 处理HTTP错误响应
      if (err.response && err.response.data) {
        showToastMessage(err.response.data.message || '加入失败，请稍后重试');
      } else {
        showToastMessage('网络错误，请稍后重试');
      }
    } finally {
      setJoinLoading(false);
    }
  };

  // 卡片操作按钮
  const getCardActions = () => {
    const actions = [
      <Tooltip title="查看详情" key="detail">
        <Button 
          type="link" 
          icon={<EyeOutlined />}
          onClick={() => navigate(`/network/${network.networkId}`)}
          style={{ color: '#1890ff', fontWeight: 500 }}
        >
          详情
        </Button>
      </Tooltip>
    ];

    if (userRole === 'admin') {
      actions.push(
        <Tooltip title="管理网络" key="manage">
          <Button 
            type="link" 
            icon={<SettingOutlined />}
            onClick={() => navigate(`/network/${network.networkId}/manage`)}
            style={{ color: '#52c41a', fontWeight: 500 }}
          >
            管理
          </Button>
        </Tooltip>
      );
    }

    if (showJoinButton) {
      actions.push(
        <Tooltip title="加入网络" key="join">
          <Button 
            type="link" 
            icon={<UserAddOutlined />}
            onClick={handleJoinNetwork}
            loading={joinLoading}
            style={{ color: '#722ed1', fontWeight: 500 }}
          >
            加入
          </Button>
        </Tooltip>
      );
    }

    return actions;
  };

  return (
    <div>
      <Card
        hoverable
        style={{ 
          borderRadius: '16px',
          border: '1px solid #f0f0f0',
          boxShadow: '0 2px 8px rgba(0, 0, 0, 0.06)',
          transition: 'all 0.3s ease',
          background: 'linear-gradient(135deg, #ffffff 0%, #fafafa 100%)'
        }}
        bodyStyle={{ 
          padding: '24px',
          background: 'transparent'
        }}
        actions={getCardActions()}
        className="network-card-custom"
      >
        <div style={{ marginBottom: '20px' }}>
          {/* 头部区域 */}
          <div style={{ 
            display: 'flex', 
            alignItems: 'center', 
            justifyContent: 'space-between',
            marginBottom: '16px'
          }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
              <Avatar 
                size={56} 
                style={{ 
                  backgroundColor: network.isPublic ? '#52c41a' : '#1890ff',
                  fontSize: '20px',
                  boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)'
                }}
                icon={network.isPublic ? <GlobalOutlined /> : <HomeOutlined />}
              >
                {!network.isPublic ? network.name.charAt(0) : null}
              </Avatar>
              <div>
                <div style={{ 
                  fontSize: '18px', 
                  fontWeight: 600, 
                  color: '#262626',
                  marginBottom: '4px'
                }}>
                  {network.name}
                </div>
                {getStatusTag(network.status)}
              </div>
            </div>
          </div>

          {/* 信息区域 */}
          <div style={{ 
            background: 'rgba(24, 144, 255, 0.04)',
            borderRadius: '12px',
            padding: '16px',
            border: '1px solid rgba(24, 144, 255, 0.1)'
          }}>
            <Space direction="vertical" size={12} style={{ width: '100%' }}>
              <div style={{ 
                display: 'flex', 
                alignItems: 'center',
                padding: '8px 12px',
                background: '#ffffff',
                borderRadius: '8px',
                border: '1px solid #f0f0f0'
              }}>
                <TeamOutlined style={{ 
                  marginRight: 8, 
                  color: '#1890ff',
                  fontSize: '16px'
                }} />
                <Text style={{ 
                  color: '#595959',
                  fontSize: '14px',
                  fontWeight: 500
                }}>
                  成员: <span style={{ color: '#1890ff', fontWeight: 600 }}>{network.memberCount}</span>
                </Text>
              </div>
              
              <div style={{ 
                display: 'flex', 
                alignItems: 'center',
                padding: '8px 12px',
                background: '#ffffff',
                borderRadius: '8px',
                border: '1px solid #f0f0f0'
              }}>
                <CalendarOutlined style={{ 
                  marginRight: 8, 
                  color: '#1890ff',
                  fontSize: '16px'
                }} />
                <Text style={{ 
                  color: '#595959',
                  fontSize: '14px',
                  fontWeight: 500
                }}>
                  {formatDate(network.createdAt)}
                </Text>
              </div>
            </Space>
          </div>
        </div>
      </Card>
      {showToast && (
        <Toast 
          message={toastMessage} 
          onClose={() => setShowToast(false)} 
        />
      )}
      <style jsx>{`
        .network-card-custom:hover {
          transform: translateY(-4px);
          box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12) !important;
        }
        
        .network-card-custom .ant-card-actions {
          background: rgba(250, 250, 250, 0.8);
          border-top: 1px solid #f0f0f0;
          border-radius: 0 0 16px 16px;
        }
        
        .network-card-custom .ant-card-actions > li {
          margin: 8px 0;
        }
        
        .network-card-custom .ant-card-actions > li > span {
          border-radius: 8px;
          transition: all 0.2s ease;
        }
        
        .network-card-custom .ant-card-actions > li > span:hover {
          background: rgba(24, 144, 255, 0.1);
        }
      `}</style>
    </div>
  );
};

export default NetworkCard;